<?php
// +----------------------------------------------------------------------
// | TwoThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.twothink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 艺品网络  82550565@qq.com <www.twothink.cn> 
// +----------------------------------------------------------------------
namespace app\common\api;

use think\Validate;
use think\Db;
use think\Exception;
/*
 * @title插件开发公共类
 * @Author: 小矮人  82550565@qq.com <www.twothink.cn>
 */
class Addon{
    public $error;//错误信息
    /*
     * @title 新增钩子
     * @param array $data 参数  ['name'=>'标识','description'=>'描述','type'=>'1']
     * @Author: 小矮人  82550565@qq.com <www.twothink.cn>
     */
    public function addHooks($data) {
        $hookModel = model('Hooks');
        $rule = [
            ['name','require|unique:hooks','钩子名称必须|钩子已存在'],
            ['description','require','钩子描述必须']
        ];
        $validate = new Validate($rule);
        if (!$validate->check($data)) {
            $this->error( $validate->getError() );
            return false;
        }
        $flag = $hookModel->allowField ( true )->save ( $data );
        if ($flag) {
            cache ( 'hooks', null );
            return true;
        } else {
            $this->error ( '新增失败' );
            return false;
        }
    }
    /*
     * @title 查询单条钩子信息
     * @param array $name 钩子名称
     * @Author: 小矮人  82550565@qq.com <www.twothink.cn>
     */
    public function findHooks($name) {
        return $data = Db::name('Hooks')->getByName($name);
    }
    /*
     * @title 删除钩子
     * @param array $name 钩子名称
     * @Author: 小矮人  82550565@qq.com <www.twothink.cn>
     */
    public function delHooks($name) {
        $gd_name = ['pageHeader','pageFooter','documentEditForm','documentDetailAfter','documentDetailBefore','documentSaveComplete','documentEditFormContent','adminArticleEdit','topicComment','app_begin'];
        if(in_array($name,$gd_name)){
            $this->error ( '系统钩子不可删除' );
            return false;
        }
        $obj = Db::name('Hooks');
        $data = $obj->getByName($name);
        $count = count(explode(',',$data['addons']));
        if($count <= 1){
            $obj->delete($data['id']);
        }
        return true;
    }
    protected function error($msg){
        $this->error = $msg;
    }
    public function getError()
    {
        return $this->error;
    }
}